{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python基本语法\n",
    "\n",
    "本课程我们将学习Python的基本语法，包括变量、数据类型、运算符和输入输出函数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 变量和数据类型\n",
    "\n",
    "### 什么是变量？\n",
    "变量是存储数据的容器，在Python中，变量无需提前声明类型，非常灵活。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 变量的基本使用\n",
    "message = \"Hello Python!\"\n",
    "number = 42\n",
    "print(message)\n",
    "print(number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 变量在实际应用中的作用\n",
    "\n",
    "变量在实际开发中有广泛的应用场景：\n",
    "1. 用户信息管理 - 存储用户姓名、年龄、账户余额等\n",
    "2. 游戏开发 - 记录玩家得分、生命值、位置坐标\n",
    "3. 数据分析 - 存储分析过程中的中间结果\n",
    "4. 网站开发 - 保存用户输入的表单数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：电商应用中的购物车\n",
    "product_name = \"笔记本电脑\"\n",
    "price = 5999.00\n",
    "quantity = 1\n",
    "is_in_stock = True\n",
    "total_cost = price * quantity\n",
    "\n",
    "print(f\"商品: {product_name}\")\n",
    "print(f\"单价: {price}元\")\n",
    "print(f\"数量: {quantity}\")\n",
    "print(f\"库存状态: {'有货' if is_in_stock else '缺货'}\")\n",
    "print(f\"总价: {total_cost}元\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 变量的命名规则\n",
    "- 只能包含字母、数字和下划线\n",
    "- 不能以数字开头\n",
    "- 不能使用Python关键字（如`if`、`for`、`while`等）\n",
    "- 区分大小写（`name`和`Name`是不同的变量）\n",
    "- 应该使用有意义的名称"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 有效的变量名\n",
    "name = \"小明\"\n",
    "age = 25\n",
    "user_score = 95.5\n",
    "is_student = True\n",
    "\n",
    "# 无效的变量名（已注释，避免运行错误）\n",
    "# 2name = \"小红\"  # 不能以数字开头\n",
    "# my-name = \"小刚\"  # 不能包含连字符\n",
    "# if = \"条件\"  # 不能使用关键字"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 基本数据类型及其应用场景\n",
    "\n",
    "#### 1. 整数 (int)\n",
    "表示整数值，如1、-10、42等。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 25\n",
    "year = 2023\n",
    "temperature = -5\n",
    "\n",
    "print(age)\n",
    "print(year)\n",
    "print(temperature)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**整数的应用场景:**\n",
    "1. 计数器 - 网站访问量统计\n",
    "2. 库存管理 - 商品数量跟踪\n",
    "3. 年龄计算 - 根据出生年份计算年龄\n",
    "4. 温度监控 - 整数部分的温度值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：商品库存管理\n",
    "initial_stock = 100\n",
    "sold_items = 37\n",
    "returned_items = 5\n",
    "current_stock = initial_stock - sold_items + returned_items\n",
    "\n",
    "print(f\"初始库存: {initial_stock}件\")\n",
    "print(f\"已售出: {sold_items}件\")\n",
    "print(f\"退货: {returned_items}件\")\n",
    "print(f\"当前库存: {current_stock}件\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 浮点数 (float)\n",
    "表示带小数点的数值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "height = 1.75\n",
    "weight = 68.5\n",
    "pi = 3.14159\n",
    "\n",
    "print(height)\n",
    "print(weight)\n",
    "print(pi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**浮点数的应用场景:**\n",
    "1. 金融计算 - 货币金额、利率、汇率\n",
    "2. 科学计算 - 物理公式、化学计算\n",
    "3. 数据分析 - 统计平均值、百分比\n",
    "4. 地理信息 - GPS坐标、距离计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：银行利息计算\n",
    "principal = 10000.00  # 本金\n",
    "interest_rate = 0.035  # 年利率3.5%\n",
    "time_years = 2.5  # 存款时间(年)\n",
    "\n",
    "# 计算单利\n",
    "interest = principal * interest_rate * time_years\n",
    "final_amount = principal + interest\n",
    "\n",
    "print(f\"本金: {principal}元\")\n",
    "print(f\"年利率: {interest_rate * 100}%\")\n",
    "print(f\"存款时间: {time_years}年\")\n",
    "print(f\"利息: {interest:.2f}元\")\n",
    "print(f\"本息合计: {final_amount:.2f}元\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. 字符串 (str)\n",
    "表示文本，用单引号或双引号括起来。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "name = \"张三\"\n",
    "message = '你好，世界！'\n",
    "address = \"北京市朝阳区\"\n",
    "\n",
    "print(name)\n",
    "print(message)\n",
    "print(address)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**字符串的应用场景:**\n",
    "1. 用户界面 - 显示文本、提示信息\n",
    "2. 数据处理 - 姓名、地址、描述等文本信息\n",
    "3. 文件操作 - 读写文本文件内容\n",
    "4. 网络应用 - URL处理、网页内容提取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：个人简历信息格式化\n",
    "first_name = \"小\"\n",
    "last_name = \"王\"\n",
    "full_name = last_name + first_name\n",
    "profession = \"软件工程师\"\n",
    "skills = \"Python, 数据分析, 网页开发\"\n",
    "years_experience = 3\n",
    "\n",
    "# 生成简历摘要\n",
    "resume = f\"\"\"\n",
    "个人简历摘要:\n",
    "姓名: {full_name}\n",
    "职业: {profession}\n",
    "技能: {skills}\n",
    "工作经验: {years_experience}年\n",
    "\"\"\"\n",
    "\n",
    "print(resume)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. 布尔值 (bool)\n",
    "表示真(True)或假(False)，常用于条件判断。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "is_student = True\n",
    "has_completed = False\n",
    "\n",
    "print(is_student)\n",
    "print(has_completed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**布尔值的应用场景:**\n",
    "1. 用户验证 - 登录状态、权限控制\n",
    "2. 程序流程控制 - 条件判断、循环终止条件\n",
    "3. 表单验证 - 检查输入是否合法\n",
    "4. 功能开关 - 启用/禁用特定功能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：网站用户登录状态管理\n",
    "is_logged_in = True\n",
    "is_admin = False\n",
    "has_premium = True\n",
    "is_first_visit = False\n",
    "\n",
    "# 根据用户状态显示不同内容\n",
    "print(\"--- 用户状态 ---\")\n",
    "print(f\"登录状态: {'已登录' if is_logged_in else '未登录'}\")\n",
    "print(f\"管理权限: {'有' if is_admin else '无'}\")\n",
    "print(f\"会员等级: {'高级会员' if has_premium else '普通会员'}\")\n",
    "print(f\"是否首次访问: {'是' if is_first_visit else '否'}\")\n",
    "\n",
    "# 根据状态组合判断\n",
    "if is_logged_in and has_premium:\n",
    "    print(\"欢迎回来，尊贵的高级会员！\")\n",
    "elif is_logged_in and not has_premium:\n",
    "    print(\"欢迎回来，普通会员！\")\n",
    "else:\n",
    "    print(\"请登录以获取更多功能！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 查看数据类型\n",
    "可以使用`type()`函数查看变量的数据类型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "name = \"小明\"\n",
    "age = 25\n",
    "height = 1.75\n",
    "is_student = True\n",
    "\n",
    "print(type(name))      # <class 'str'>\n",
    "print(type(age))       # <class 'int'>\n",
    "print(type(height))    # <class 'float'>\n",
    "print(type(is_student))  # <class 'bool'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 类型转换\n",
    "可以在不同数据类型之间进行转换："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 字符串转整数\n",
    "age_str = \"25\"\n",
    "age = int(age_str)\n",
    "print(age + 5)  # 输出30\n",
    "\n",
    "# 整数转字符串\n",
    "year = 2023\n",
    "year_str = str(year)\n",
    "print(\"今年是\" + year_str + \"年\")  # 输出\"今年是2023年\"\n",
    "\n",
    "# 字符串转浮点数\n",
    "price_str = \"19\"\n",
    "price = float(price_str)\n",
    "print(price * 2)  # 输出39.98"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 注释和缩进规则\n",
    "\n",
    "### 注释\n",
    "注释是程序中不会被执行的文本，用于解释代码或暂时禁用某些代码。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这是一个单行注释\n",
    "name = \"小明\"  # 这也是注释，解释了变量的用途\n",
    "\n",
    "\"\"\"\n",
    "这是多行注释\n",
    "可以跨越多行\n",
    "通常用于函数或模块的说明\n",
    "\"\"\"\n",
    "'''\n",
    "nihao\n",
    "'''\n",
    "\n",
    "print(name)  # 注释不会影响代码执行"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 缩进规则\n",
    "Python使用缩进来表示代码块，而不是大括号或关键字。正确的缩进对Python程序至关重要！\n",
    "\n",
    "- 同一级别的代码必须有相同的缩进\n",
    "- 通常使用4个空格作为一个缩进级别\n",
    "- 建议使用空格而不是Tab键进行缩进（或将编辑器设置为Tab键转换为空格）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 正确的缩进示例\n",
    "age = 20\n",
    "if age >= 18:\n",
    "    print(\"成年人\")\n",
    "    print(\"可以投票\")\n",
    "else:\n",
    "    print(\"未成年\")\n",
    "    print(\"不能投票\")\n",
    "print(\"111\")\n",
    "# 错误的缩进示例（已注释，避免运行错误）\n",
    "# if age >= 18:\n",
    "# print(\"成年人\")  # 这行会引发IndentationError错误"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. 基本运算符及其应用场景\n",
    "\n",
    "### 算术运算符\n",
    "用于执行基本的数学运算："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 10\n",
    "b = 3\n",
    "\n",
    "print(a + b)    # 13 (加法)\n",
    "print(a - b)    # 7 (减法)\n",
    "print(a * b)    # 30 (乘法)\n",
    "print(a / b)    # 3.3333333333333335 (除法)\n",
    "print(a % b)    # 1 (取余，10除以3的余数)\n",
    "print(a ** b)   # 1000 (幂运算，10的3次方)\n",
    "print(a // b)   # 3 (整除，舍去小数部分)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**算术运算符的应用场景:**\n",
    "1. 电子商务 - 购物车计算、折扣计算\n",
    "2. 金融应用 - 投资回报计算、贷款利息\n",
    "3. 游戏开发 - 得分计算、角色属性调整\n",
    "4. 数据分析 - 数据处理、统计计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：电商购物车计算\n",
    "item1_price = 299.99\n",
    "item2_price = 99.50\n",
    "item3_price = 149.85\n",
    "quantity1 = 2\n",
    "quantity2 = 1\n",
    "quantity3 = 3\n",
    "\n",
    "# 计算小计\n",
    "subtotal1 = item1_price * quantity1\n",
    "subtotal2 = item2_price * quantity2\n",
    "subtotal3 = item3_price * quantity3\n",
    "\n",
    "# 计算总金额\n",
    "total_before_discount = subtotal1 + subtotal2 + subtotal3\n",
    "\n",
    "# 应用折扣（85折）\n",
    "discount_rate = 0.85\n",
    "final_total = total_before_discount * discount_rate\n",
    "\n",
    "# 计算节省金额\n",
    "saved_amount = total_before_discount - final_total\n",
    "\n",
    "print(f\"商品1: {quantity1}件 x {item1_price}元 = {subtotal1}元\")\n",
    "print(f\"商品2: {quantity2}件 x {item2_price}元 = {subtotal2}元\")\n",
    "print(f\"商品3: {quantity3}件 x {item3_price}元 = {subtotal3}元\")\n",
    "print(f\"小计: {total_before_discount}元\")\n",
    "print(f\"折扣: 85折\")\n",
    "print(f\"最终总价: {final_total:.2f}元\")\n",
    "print(f\"节省: {saved_amount:.2f}元\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 比较运算符\n",
    "用于比较两个值，返回布尔值（True或False）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 10\n",
    "b = 5\n",
    "\n",
    "print(a == b)    # False (等于)\n",
    "print(a != b)    # True (不等于)\n",
    "print(a > b)     # True (大于)\n",
    "print(a < b)     # False (小于)\n",
    "print(a >= b)    # True (大于等于)\n",
    "print(a <= b)    # False (小于等于)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 逻辑运算符\n",
    "用于组合条件表达式："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = True\n",
    "b = False\n",
    "\n",
    "print(a and b)   # False (逻辑与：两者都为True才返回True)\n",
    "print(a or b)    # True (逻辑或：至少一个为True就返回True)\n",
    "print(not a)     # False (逻辑非：取反)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 赋值运算符\n",
    "用于给变量赋值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 10\n",
    "a += 5      # 等价于 a = a + 5\n",
    "print(a)    # 15\n",
    "\n",
    "b = 10\n",
    "b -= 3      # 等价于 b = b - 3\n",
    "print(b)    # 7\n",
    "\n",
    "c = 10\n",
    "c *= 2      # 等价于 c = c * 2\n",
    "print(c)    # 20"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. 输出函数及其应用场景\n",
    "\n",
    "### 输出：print()函数\n",
    "我们已经见过print()函数，它用于在屏幕上显示信息："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基本用法\n",
    "name = \"25\"\n",
    "print(f\"你好，{name}！\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：简易聊天机器人\n",
    "print(\"=\" * 30)\n",
    "print(\"欢迎使用Python聊天机器人\")\n",
    "print(\"=\" * 30)\n",
    "\n",
    "user_name = \"小明\"\n",
    "print(f\"你好，{user_name}！很高兴认识你。\")\n",
    "\n",
    "feeling = \"好\"\n",
    "\n",
    "if feeling == \"好\":\n",
    "    print(\"太棒了！希望你的好心情能持续一整天！\")\n",
    "elif feeling == \"一般\":\n",
    "    print(\"生活就是起起落落，明天会更好的！\")\n",
    "elif feeling == \"不好\":\n",
    "    print(\"别担心，每个人都有不好的时候，有什么我能帮你的吗？\")\n",
    "else:\n",
    "    print(\"不管怎样，希望接下来的一天你过得愉快！\")\n",
    "\n",
    "hobby = \"篮球\"\n",
    "print(f\"{hobby}是个很棒的爱好！我也对此很感兴趣。\")\n",
    "\n",
    "print(f\"很高兴和你聊天，{user_name}！下次再见！\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
